package com.apexwear.apexutils.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.RecyclerView;

import com.apexwear.apexutils.R;
import com.apexwear.apexutils.api.OnItemClickListener;
import com.apexwear.apexutils.model.Ota;

import java.util.List;

public class AdapterOtaList extends RecyclerView.Adapter<AdapterOtaList.OtaHold> {
    Context mContext;
    List<Ota> otaList;
    OnItemClickListener onItemClickListener;

    public AdapterOtaList(Context mContext, List<Ota> otaList) {
        this.mContext = mContext;
        this.otaList = otaList;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @NonNull
    @Override
    public OtaHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View adapterView = LayoutInflater.from(mContext).inflate(R.layout.adapter_ota_list, parent, false);
        return new OtaHold(adapterView);
    }

    @Override
    public void onBindViewHolder(@NonNull OtaHold holder, int position) {
        if (otaList == null || otaList.isEmpty()) {
            return;
        }
        Ota ota = otaList.get(position);
        holder.typeText.setText(ota.getWatchName() + "一" + ota.getFileType());
        holder.fileText.setText(ota.getFileName());
        holder.updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.clickListener(position);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return otaList == null ? 0 : otaList.size();
    }

    class OtaHold extends RecyclerView.ViewHolder {
        AppCompatButton updateButton;
        TextView typeText;
        TextView fileText;

        public OtaHold(@NonNull View itemView) {
            super(itemView);
            updateButton = itemView.findViewById(R.id.ota_updated);
            typeText = itemView.findViewById(R.id.type_name);
            fileText = itemView.findViewById(R.id.file_name);
        }
    }

    public void destroyAdapter() {
        mContext = null;
        onItemClickListener = null;
        if (otaList != null) {
            otaList.clear();
            otaList = null;
        }
    }
}
